package com.cloudspace.jindun.fragment;

import android.content.DialogInterface;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.error.VolleyError;
import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.locate.LocateSuperviseActivity;
import com.cloudspace.jindun.callback.AuthCodeInputCallback;
import com.cloudspace.jindun.manager.MyLocationManager;
import com.cloudspace.jindun.model.LocateArea;
import com.cloudspace.jindun.model.LocateAreaResult;
import com.cloudspace.jindun.model.LocatePerson;
import com.cloudspace.jindun.network.api.API;
import com.cloudspace.jindun.network.base.ApiCallback;
import com.cloudspace.jindun.ui.AuthDialog;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.MMAlert;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;
import com.cloudspace.jindun.window.MyPopupMenu;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.linphone.LinphoneService;

import org.apache.http.HttpStatus;

import java.util.ArrayList;
import java.util.Random;

/**
 * Created by zengxianhua on 16/12/19.
 */

public class LocateFragment extends BaseFragment implements OnMapReadyCallback {
    public static final String TAG = LocateFragment.class.getSimpleName();

    private static final String ARG_SECTION_NUMBER = "section_number";
    private MapView mMap;
    public final int MY_PERMISSIONS_REQUEST_LOCATE = 100;

    private View superViseView;
    private MyPopupMenu menuPopup;
    private View.OnClickListener superViseListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showAuthDialog();
        }
    };
    private AuthDialog mEnterCodeDlg;

    private void showAuthDialog() {
        if (mEnterCodeDlg == null){
            mEnterCodeDlg = new AuthDialog(getActivity());
        }

        mEnterCodeDlg.show(new AuthCodeInputCallback() {
            @Override
            public void onFinish(String code) {
                valid(code);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void valid(String code) {
        API.getInstance().getLocateApi().checkCode(TAG, code, new ApiCallback<LocateAreaResult>() {
            @Override
            public void handleResult(LocateAreaResult result, VolleyError error) {
                if (mEnterCodeDlg != null){
                    mEnterCodeDlg.hide();
                }

                if (result != null){
                    if (result.status == HttpStatus.SC_OK){
//                        testData(result);
                        LocateSuperviseActivity.showActivity(getActivity(), result);
                    }else{
                        showValidErrorDlg();
                    }
                }else{
                    ToastMaker.showToastShort(R.string.generic_error);
                }
            }
        }.toastActionError());
    }

    private int getRandomInt(){
        int randomInt = new Random().nextInt(4);
        return randomInt%4;
    }

    private void testData(LocateAreaResult result) {
        if (ObjUtil.isEmpty(result)){
            return;
        }

        result.data = new ArrayList<>();

        double randomDouble[] = {0.01, 0.03, 0.05, 0.02};
        int multi[]= {1, 2, 3, 5};

        for (int i = 0; i < 5 ; ++i){
            LocateArea area = new LocateArea();
            area.areaId = String.valueOf(i);
            area.areaName = "area " + i;
            area.areaSafeLevel = String.valueOf(i);
            area.areaCoordinate = "xxx";

            area.perList = new ArrayList<>();
            for (int j = 0; j < 5; ++j){
                LocatePerson person = new LocatePerson();
                person.areaName = "area " + i;

                person.userId = UserSessionManager.getInstance().getUserId();
                person.userCoordinateJ = MyLocationManager.getInstance().getMyLocation().getLongitude() +
                        multi[getRandomInt()]*randomDouble[getRandomInt()];
                person.userCoordinateW = MyLocationManager.getInstance().getMyLocation().getLatitude() +
                        multi[getRandomInt()]*randomDouble[getRandomInt()];
                person.userOnlineDateValue = "2017-03-14 00:00:00";
                person.userName = UserSessionManager.getInstance().getSipUserName();

                area.perList.add(person);
            }

            result.data.add(area);
        }
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_dingwei, container, false);

        mMap = (MapView) rootView.findViewById(R.id.mapview);
        mMap.onCreate(savedInstanceState);

        menuPopup = new MyPopupMenu(getActivity());
        superViseView = rootView.findViewById(R.id.manageImg);
        superViseView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                menuPopup.showOrHideOverflow(superViseView,
                        getResources().getString(R.string.locate_supervise),
                        "",
                        superViseListener,
                        null
                );
            }
        });


        try {
            MapsInitializer.initialize(getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        int errorCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this.getActivity());

        if (ConnectionResult.SUCCESS == errorCode) {
            mMap.getMapAsync(this);
        }else{
            MMAlert.showAlert(getActivity(),
                    JindunApp.getInstance().getResources().getString(R.string.permission_locate)
                    );
        }

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mMap != null){
            mMap.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mMap != null){
            mMap.onPause();
        }
    }

    @Override
    public void onFragmentCreated(Bundle savedInstanceState) {

    }

    @Override
    public void updateContent() {

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        Location location = LinphoneService.instance().getLocation();

        if (location != null) {
            LatLng curLocation = new LatLng(location.getLatitude(), location.getLongitude());

            googleMap.setMyLocationEnabled(true);
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLocation, 13));

            googleMap.addMarker(new MarkerOptions()
                    .title("me")
                    .position(curLocation));
        }else{
            ToastMaker.showToastShort(R.string.locate_fail);
        }
    }

    public  void showValidErrorDlg(){
        MMAlert.showAlert(getActivity(), getResources().getString(R.string.invalid_code),
                getResources().getString(R.string.info),
                getResources().getString(R.string.iknow), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
    }
}
